from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.views.generic import FormView
from lib.django.views import UpdateView
from media.lib.forms import UploadFileForm
from media.lib.utils import store_permanents
from .. import forms
from .lib import template_path
from django.contrib.auth import update_session_auth_hash
from django.contrib import messages
from django.utils.translation import gettext_lazy as _

User = get_user_model()

class SettingsProfileUpdateView(
    LoginRequiredMixin,
    UpdateView
):
    model = User
    form_class = forms.SettingsProfileForm
    template_name = template_path("settings/form_base.html")
    success_url = reverse_lazy("user:settings/profile")

    def get_object(self, queryset=None):
        return self.request.user

# refers to django.contrib.auth.auth_views.PasswordChangeView
class SettingsAccountUpdateView(
    LoginRequiredMixin,
    FormView
):
    model = User
    form_class = forms.SettingsAccountForm
    template_name = template_path("settings/form_base.html")
    success_url = reverse_lazy("user:settings/account")

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["user"] = self.request.user
        return kwargs

    def form_valid(self, form):
        form.save()
        # Updating the password logs out all other sessions for the user
        # except the current one.
        update_session_auth_hash(self.request, form.user)
        messages.add_message(self.request, messages.SUCCESS, _("密码更新成功"))
        return super().form_valid(form)

class SettingsResumeManagementView(
    LoginRequiredMixin,
    FormView
):
    model = get_user_model()
    form_class = UploadFileForm
    template_name = template_path("settings/resume.html")
    success_url = reverse_lazy("user:settings/resume")

    def get_object(self, queryset=None):
        return self.request.user

    def form_valid(self, form):
        user = self.request.user
        researcher = user.researcher_profile
        file_ids = form.cleaned_data.get('files', [])
        store_permanents(file_ids, researcher, 'resume', user)
        return super().form_valid(form)

    def dispatch(self, request, *args, **kwargs):
        user = self.request.user
        if not user.is_researcher:
            return self.handle_no_permission()
        return super().dispatch(request, *args, **kwargs)






    
